<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button class="ml-4" @click="handleExport" :loading="exportLoading"> 导出 </el-button>
      </el-form-item>
      <el-form ref="forms" :model="list" :rules="rules">
        <el-table v-if="refreshTable" v-loading="loading" :data="list">
          <el-table-column :show-overflow-tooltip="true" label="编号" type="index" />
          <el-table-column :show-overflow-tooltip="true" label="字段名称">
            <template #default="scope">
              <div>
                <el-form-item
                  :prop="`list[${scope.$index}].name`"
                  :rules="ctmRuleName(scope.$index)"
                >
                  <ns-input
                    @input="handleChange"
                    v-model="scope.row.name"
                    placeholder="请输入字段名称"
                  />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="填写方式" prop="fillingMethod">
            <template #default="scope">
              <div>
                <el-form-item
                  :prop="`list.${scope.$index}.fillingMethod`"
                  :rules="ctmRuleFill(scope.$index)"
                >
                  <el-select
                    v-model="scope.row.fillingMethod"
                    placeholder="请选择填写方式"
                    :disabled="scope.$index < 3"
                    clearable
                    @change="handleChange"
                  >
                    <el-option label="输入框" value="输入框" />
                    <el-option label="选择器" value="选择器" />
                    <el-option label="日期" value="日期" />
                  </el-select>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="关联其他标准字段">
            <template #default="scope">
              <div>
                <el-form-item :prop="`list.${scope.$index}.relevance`">
                  <el-cascader
                    v-model="scope.row.relevance"
                    placeholder="请选择关联其他标准字段"
                    :props="cascaderProps"
                    :options="relevanceTree"
                    filterable
                    clearable
                  />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="是否必填	">
            <template #default="scope">
              <div>
                <el-form-item
                  :prop="`list[${scope.$index}].required`"
                  :rules="ctmRule2(scope.$index)"
                >
                  <el-radio-group v-model="scope.row.required">
                    <el-radio label="1" size="large" :disabled="scope.row.display == '2'"
                      >必填</el-radio
                    >
                    <el-radio label="2" size="large">非必填</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="是否显示">
            <template #default="scope">
              <div>
                <el-form-item
                  :prop="`list[${scope.$index}].display`"
                  :rules="ctmRule2(scope.$index)"
                >
                  <el-radio-group v-model="scope.row.display">
                    <el-radio label="1" size="large">显示</el-radio>
                    <el-radio label="2" size="large" :disabled="scope.row.required == '1'"
                      >不显示</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import {
  assuranceList,
  assuranceUpdateBatch,
  assuranceRelevanceTree,
  assuranceExportExcel
} from '@/api/dataStandards/assurance/index'
import download from '@/utils/download'
import { FormRules } from 'element-plus'
import Item from '../device/DeviceList/Item.vue'
const emit = defineEmits(['assuranceChange'])
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const message = useMessage() // 消息弹窗
const route = useRoute()
const { t } = useI18n() // 国际化
const refreshTable = ref(true)
const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据

const inputValue = ref('')
const InputRef = ref()

const props = defineProps({
  type: {
    type: Number
  },
  id: {
    type: String
  }
})

const handleClose = (tagIndex, presetContentMap) => {
  presetContentMap.splice(tagIndex, 1)
}

const showInput = (row) => {
  row.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = (row) => {
  if (inputValue.value) {
    row.presetContentMap.push(inputValue.value)
  }
  row.inputVisible = false
  inputValue.value = ''
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await assuranceList({
      dataStandardId: route.query.id
    })
    console.log('data', data)
    list.value = data.map((item) => {
      return {
        ...item,
        inputVisible: false,
        presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
      }
    })
  } finally {
    loading.value = false
  }
}

const save = async () => {
  await forms.value.validate(async (valid, fields) => {
    if (valid) {
      
      const transformedList = list.value
        .filter((item) => {
          // ✅ 过滤规则：name 和 fillingMethod 至少有一个有值，才认为是有效行
          // 如果你希望更严格：两个都必须有值，可以改成 &&
          const hasName = item.name && item.name.trim() !== ''
          const hasFillingMethod = item.fillingMethod

          // 只要 name 或 fillingMethod 有一个有值，就保留（说明用户开始填写了）
          return hasName || hasFillingMethod
        })
        .map((item) => {
          // 返回新对象，转换 required/display 为数字，处理 presetContent
          return {
            ...item,
            required: Number(item.required),
            display: Number(item.display),
            presetContent: JSON.stringify(item.presetContentMap)
          }
        })


      // 3. 如果没有有效数据，提示用户
      if (transformedList.length === 0) {
        message.warning('没有有效数据可保存')
        return
      }
      console.log('transformedList.value:', transformedList)
      const data = await assuranceUpdateBatch(transformedList)
      console.log('data', data)
      if (data) {
        message.success('操作成功')
        emit('assuranceChange')
      }
    }
  })
}

// 导出
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await assuranceExportExcel({
      dataStandardId: route.query.id
    })
    download.excel(data, '数据保护标准.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const cascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})
const relevanceTree = ref()
const getInfoRelevanceTree = async () => {
  const data = await assuranceRelevanceTree({ standardId: props.id, type: props.type })

  relevanceTree.value = traverseTree(data)
}
function traverseTree(data) {
  const updatedTree = []

  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.pid == '-1') {
      node.disabled = true
    }
    updatedTree.push(node)

    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }

  return updatedTree
}

//自定义表格表单校验
// name  fillingMethod relevance 全部为空或者全部填过
const forms = ref()
const validatePass = async (rule: any, value: any, callback: any, index: number) => {
  if (list.value[index].name && list.value[index].fillingMethod) {
    callback()
  } else if (
    !list.value[index].name &&
    !list.value[index].fillingMethod &&
    !list.value[index].relevance
  ) {
    callback()
  }
  callback(new Error('必填项'))
}
const ctmRule = (index: number) => {
  return [
    {
      validator: async (rule: any, value: any, callback: any) => {
        validatePass(rule, value, callback, index)
      }
    }
  ]
}
const ctmRuleName = (index: numbe) => {
  return [
    {
      validator: async (rule: any, value: any, callback: any) => {
        if (list.value[index].name) {
          if (list.value[index].fillingMethod) {
            callback()
          } else {
            callback('字段名称和填写方式必填')
          }
        } else {
          if (list.value[index].fillingMethod) {
            callback('字段名称和填写方式必填')
          } else {
            callback()
          }
        }
      }
    }
  ]
}

const ctmRuleFill = (index: numbe) => {
  return [
    {
      validator: async (rule: any, value: any, callback: any) => {
        if (list.value[index].name) {
          if (list.value[index].fillingMethod) {
            callback()
          } else {
            callback('字段名称和填写方式必填')
          }
        } else {
          if (list.value[index].fillingMethod) {
            callback('字段名称和填写方式必填')
          } else {
            callback()
          }
        }
      }
    }
  ]
}

const validatePass2 = async (rule: any, value: any, callback: any, index: number) => {
  if (list.value[index].name || list.value[index].fillingMethod) {
    if (list.value[index].required == 0 || list.value[index].display == 0) {
      callback(new Error('必填项'))
    }
    callback()
  } else {
    callback()
  }
}
const ctmRule2 = (index: number) => {
  return [
    {
      validator: async (rule: any, value: any, callback: any) => {
        validatePass2(rule, value, callback, index)
      }
    }
  ]
}

function debounce(func, delay) {
  let timer = null
  return function () {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, arguments)
    }, delay)
  }
}
const handleChange = () => {
  forms.value.validate()
}

onMounted(() => {
  getList()
  getInfoRelevanceTree()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
